package transcode

import (
	"context"
	"encoding/json"
	"net/url"
	"strings"
	"time"

	"code.byted.org/bytertc/whiteboard_server/biz/api"
	"code.byted.org/bytertc/whiteboard_server/biz/service/transcode/task"
	"code.byted.org/gopkg/logs/v2/log"
	"github.com/google/uuid"
	"github.com/pkg/errors"
)

func (m *manager) HandleWpsCallbackFileDetail(ctx context.Context, request *api.WpsCallbackFileDetailRequest) (*api.WpsCallbackFileDetailResponse, error) {
	t, err := m.repo.GetTranscodeTaskByFileID(ctx, request.FileID)
	if err != nil {
		return nil, err
	}
	return &api.WpsCallbackFileDetailResponse{
		ID:         t.FileID,
		Name:       t.FileName,
		Version:    1,
		Size:       t.FileSize,
		CreateTime: time.Now().Unix(),
		ModifyTime: time.Now().Unix(),
		CreatorID:  t.UserId,
		ModifierID: t.UserId,
	}, nil

}
func (m *manager) HandleWpsCallbackDownload(ctx context.Context, request *api.WpsCallbackDownloadRequest) (*api.WpsCallbackDownloadResponse, error) {
	t, err := m.repo.GetTranscodeTaskByFileID(ctx, request.FileID)
	if err != nil {
		return nil, err
	}
	tt := &task.Task{}
	err = json.Unmarshal([]byte(t.Meta), tt)
	if err != nil {
		return nil, err
	}
	resource, err := url.QueryUnescape(tt.Resource)
	if err != nil {
		return nil, err
	}
	return &api.WpsCallbackDownloadResponse{
		URL: resource,
	}, nil
}
func (m *manager) HandleWpsCallbackPermission(ctx context.Context, request *api.WpsCallbackPermissionRequest) (*api.WpsCallbackPermissionResponse, error) {
	t, err := m.repo.GetTranscodeTaskByFileID(ctx, request.FileID)
	if err != nil {
		return nil, err
	}
	if t.AppId != request.AppID {
		return nil, errors.New("AppID not match")
	}
	return &api.WpsCallbackPermissionResponse{
		UserID:   strings.Replace(uuid.NewString(), "-", "", -1),
		Read:     1,
		Update:   0,
		Download: 1,
		Rename:   0,
		History:  0,
		Copy:     1,
		Print:    1,
		Saveas:   0,
		Comment:  0,
	}, nil
}

func (m *manager) HandleWpsCallbackNotify(ctx context.Context, request *api.WpsCallbackNotifyRequest) error {
	if request.Type != "session_open" {
		return nil
	}
	log.V1.CtxInfo(ctx, "wps session_open callback,file_id:%s,content:%v", request.FileID, request.Content)
	return nil
}
